      1  import java.util.Stack;

      2

      3  /**

      4     This program simulates an undo stack. Note that operations

      5     must be undone in the opposite order in which they are first

      6     issued.

      7  */

      8  public class StackDemo

      9  {

     10     public static void main(String[] args)

     11     {

     12        Stack<String> commands = new Stack<String>();

     13        commands.push("Insert 'Hello'");

     14        commands.push("Insert ','");

     15        commands.push("Insert ' '");

     16        commands.push("Insert 'World'");

     17        commands.push("Insert '?'");

     18        commands.push("Delete '?'");

     19        commands.push("Insert '!'");

     20

     21        // Now we undo the last four commands

     22        for (int i = 1; i <= 4; i++)

     23        {

     24           String command = commands.pop();

     25           System.out.println("Undo " + command);

     26        }

     27     }

     28  }